package wensheng.stu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import wensheng.stu.common.BaseContext;
import wensheng.stu.common.R;
import wensheng.stu.dto.OrderDto;
import wensheng.stu.entity.OrderDetail;
import wensheng.stu.entity.Orders;
import wensheng.stu.service.OrderDetailService;
import wensheng.stu.service.OrdersService;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;



    @GetMapping("/page")
    public R<Page> page(int page, int pageSize){

        Page<Orders> detailPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Orders::getOrderTime);

        ordersService.page(detailPage,queryWrapper);
        return R.success(detailPage);

    }



    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){

        log.info("订单数据,{}",orders);
        ordersService.submit(orders);
        return R.success("下单成功");
    }


    @GetMapping("/userPage")
    public R<Page> userPage(int page , int pageSize){

        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrderDto> orderDtoPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        queryWrapper.orderByDesc(Orders::getOrderTime);
        ordersService.page(ordersPage,queryWrapper);

        LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();

        List<Orders> ordersList = ordersPage.getRecords();

        List<OrderDto> collect = ordersList.stream().map((item) -> {
            OrderDto orderDto = new OrderDto();
            Long id = item.getId();
            List<OrderDetail> orderListByOrderId = ordersService.getOrderListByOrderId(id);
            BeanUtils.copyProperties(item, orderDto);
            orderDto.setOrderDetailList(orderListByOrderId);
            return orderDto;
        }).collect(Collectors.toList());
        BeanUtils.copyProperties(ordersPage,orderDtoPage,"records");
        orderDtoPage.setRecords(collect);
        return R.success(orderDtoPage);

    }

    @PutMapping
    public R<String> dishSend(@RequestBody  Orders orders){

        if(orders.getId()==null||orders.getStatus()==null){
            return R.error("信息传送错误");
        }
        orders.setStatus(3);
            ordersService.updateById(orders);
        return R.success("派送成功");
    }



}
